package com.share.interceptor;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;

import java.lang.reflect.Method;
import java.sql.Statement;

/**
 * author:caifan
 * date:2020/2/7
 */
@Intercepts({@Signature(
        type= StatementHandler.class,
        method = "query",
        args = {Statement.class, ResultHandler.class})})
public class StatementInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        System.out.println("StatementInterceptor:");
        MetaObject metaObject = SystemMetaObject.forObject(invocation.getTarget());
        System.out.println("+++++++++");
        System.out.println("metaObject:" + metaObject.toString());
        System.out.println("+++++++++++");
        Object[] args = invocation.getArgs();
        int i = 0;
        for (Object obj : args) {
            i++;
            if (null != obj) {
                System.out.println(i + " " + obj.toString());
            }
        }

        Method method = invocation.getMethod();
        System.out.println("method:" + method.getName());
        Object target = invocation.getTarget();
        System.out.println("target:" + target.toString());
        RoutingStatementHandler handler  = (RoutingStatementHandler) target;
        System.out.println(handler.getBoundSql().getSql());
        Object proceed = invocation.proceed();
        System.out.println("proceed:" + proceed.toString());
        System.out.println("===============");
        return proceed;
    }
}
